﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Ymatou.CommonService
{
    public class PagerInfoExP : PagerInfoEx
    {
        public PagerInfoExP(PagerInfo info) :
            this(info.PageIndex, info.PageSize, info.RecordCount)
        {
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="PagerInfo" /> class.
        /// </summary>
        /// <param name="pageIndex">当前页码(从1开始)</param>
        /// <param name="pageSize">页长</param>
        /// <param name="recordCount">记录总数</param>
        /// <Author>binbin@CHENEY-NOTEBOOK 2010/3/28 15:20</Author>
        public PagerInfoExP(int pageIndex, int pageSize, int recordCount)
            : base(pageIndex, pageSize, recordCount)
        {
        }


        /// <summary>
        ///     Initializes a new instance of the <see cref="PagerInfo" /> class.
        /// </summary>
        /// <param name="pageIndex">当前页码(从1开始)</param>
        /// <param name="pageSize">页长</param>
        /// <param name="recordCount">记录总数</param>
        public PagerInfoExP(int? pageIndex, int? pageSize, int recordCount)
            : base(pageIndex, pageSize, recordCount)
        {
        }

        public override string GetPageUrl(int page)
        {
            var requestUrl = CurrentUrl;
            string pageLinkText = "";

            var pattern = string.Format(@"-{0}(\d+)|-{0}", PagePrefix.ToLower());
            Regex regexPagePattern = new Regex(pattern, RegexOptions.IgnoreCase);

            MatchCollection matchResults = regexPagePattern.Matches(requestUrl);

            if (matchResults.Count > 0)
            {
                pageLinkText = requestUrl.Replace(matchResults[0].ToString(), "-" + PagePrefix.ToLower() + "[$page$]");
            }
            else if (requestUrl.IndexOf("?") < 0)
            {
                pageLinkText = requestUrl + "-" + PagePrefix.ToLower() + "[$page$]";
            }
            else
            {
                var mainUrl = requestUrl.Substring(0, requestUrl.IndexOf("?"));
                var paraUrl = requestUrl.Substring(requestUrl.IndexOf("?"));
                pageLinkText = mainUrl + "-" + PagePrefix.ToLower() + "[$page$]" + paraUrl;
            }
            return pageLinkText.Replace("[$page$]", page.ToString());
        }
    }
}
